/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.huaweiocr;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.third.huaweiocr.constant.HuaweiOcrConstant;
import org.jeecg.modules.third.huaweiocr.ocr.HWOcrClientAKSK;
import org.jeecg.modules.third.huaweiocr.ocr.HWOcrClientToken;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 华为云OCR
 *
 * @author duanlikao
 * @created 2021/4/20
 * https://support.huaweicloud.com/sdkreference-ocr/ocr_04_0007.html
 */
@Service
public class HuaweiOcrService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HuaweiOcrService.class);

   // @Value(value="${huaweiocr.username}")
    private String USERNAME ;
   // @Value(value="${huaweiocr.password}")
    private String PASSWORD;

    private String  DOMAINNAME	= USERNAME;

   // @Value(value="${huaweiocr.projectid}")
    private String  PROJECT_ID		;
    //@Value(value="${huaweiocr.projectname}")
    private String  PROJECTNAME		;
   // @Value(value="${huaweiocr.access_key_id}")
    private String ACCESS_KEY_ID ;
   // @Value(value="${huaweiocr.secret_access_key}")
    private String SECRET_ACCESS_KEY;


    public  String getURL(String urlType){
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getHuaweiocrIzUse()){
            LOGGER.info("华为云OCR识别服务暂未开启,请联系管理员。");
            return StringUtils.EMPTY;
            // throw new JeecgBootException("华为云OCR识别服务暂未开启,请联系管理员。");

        }

        String url = StringUtils.EMPTY;
        if(StringUtils.isNotEmpty(urlType)){
            //"https://"+HuaweiOcrConstant.ENDPOINT+
            url = "/v2/"+systemConfig.getHuaweiocrProjectid() + "/ocr/" +urlType;
        }
        return url;
    }


//    public static void main(String[] args) throws IOException, URISyntaxException {
//        String imgPath  = "/Users/duanlikao/Downloads/12345.jpeg";
//        String httpUri = HuaweiOcrService.getURL(HuaweiOcrConstant.URL_PATH_TRANSPORTATION_LICENSE);
//        String side = "";//back
//       String a =  HuaweiOcrService.getInfoByToken(  imgPath , httpUri, side);
//       System.out.println(a);
//    }

    public  String getInfoByToken( String imgPath ,String httpUri,String side) throws URISyntaxException, UnsupportedOperationException, IOException {

        String username = USERNAME;
        String password = PASSWORD;
        String domainName = username ; //If the current user is not an IAM user, the domainName is the same as the userName.
        String regionName = PROJECTNAME;
        JSONObject params = new JSONObject();
        if(StringUtils.isNotEmpty(side)){
            String sideKey = "side";
            String sideValue = side;
            params.put(sideKey, sideValue);
            params.put("return_issuing_authority", true);
        }
        try {
            HWOcrClientToken ocrClient = new HWOcrClientToken(domainName, username, password, regionName);
            HttpResponse response = ocrClient.RequestOcrServiceBase64(httpUri, imgPath, params);
//            LOGGER.info("HuaweiOcrService getInfoByToken response :{}",response);
            String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
            return DecodeResponse(content);
        }
        catch (Exception e) {
            LOGGER.info("HuaweiOcrService getInfoByToken Exception :{}",e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    public  String getInfoByAKSK(String imgPath ,String httpUri,String side) throws URISyntaxException, UnsupportedOperationException, IOException{

        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getHuaweiocrIzUse()){
            LOGGER.info("华为云OCR识别服务暂未开启,请联系管理员。");
            return StringUtils.EMPTY;
            // throw new JeecgBootException("华为云OCR识别服务暂未开启,请联系管理员。");
        }
        String AK= systemConfig.getHuaweiocrKeyId(); //AK from authentication
        String SK= systemConfig.getHuaweiocrSecret(); //SK from authentication
        String regionName= systemConfig.getHuaweiocrProjectname(); //region name of the service
//        String  urlType = HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE;
//        String httpUri = getURL( urlType);

        JSONObject params = new JSONObject();
        if(StringUtils.isNotEmpty(side)){
            String sideKey = "side";
            String sideValue = side;
            params.put(sideKey, sideValue);
            params.put("return_issuing_authority", true);
        }

        try {
            HWOcrClientAKSK ocrClient=new HWOcrClientAKSK(regionName, AK, SK);
            HttpResponse response=ocrClient.RequestOcrServiceBase64(httpUri, imgPath, params);
//            LOGGER.info("HuaweiOcrService getInfoByAKSK response :{}",response);
            String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
//            LOGGER.info("HuaweiOcrService getInfoByAKSK content :{}",content);
            return DecodeResponse(content);
        } catch (Exception e) {
            LOGGER.info("HuaweiOcrService getInfoByAKSK Exception :{}",e.getMessage());
        }
        return StringUtils.EMPTY;
    }


    private  String TokenRequest() throws URISyntaxException, UnsupportedOperationException, IOException{
        /*
         * Token demo code
         * */
        String username = USERNAME;
        String password = PASSWORD;
        String domainName = DOMAINNAME; //If the current user is not an IAM user, the domainName is the same as the userName.
        String regionName = PROJECTNAME;
        String  urlType = HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE;
        String httpUri = getURL( urlType);
        String imgPath = "./data/vat-invoice-demo.jpg";//File path or URL of the image to be recognized.

        // Set params except image
        JSONObject params = new JSONObject();
        List <String> typeList = new ArrayList <>();
        typeList.add("vat_invoice");
        typeList.add("id_card_portrait_side");
        params.put("type_list", typeList);
        try {
            HWOcrClientToken ocrClient= new HWOcrClientToken(domainName, username, password, regionName);
            HttpResponse response=ocrClient.RequestOcrServiceBase64(httpUri, imgPath, params);
//            LOGGER.info("HuaweiOcrService TokenRequest response :{}",response);
            String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
//            LOGGER.info("HuaweiOcrService TokenRequest content :{}",content);
            return DecodeResponse(content);
        }catch (Exception e) {
            LOGGER.info("HuaweiOcrService TokenRequest Exception :{}",e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    private  String AkskRequest() throws URISyntaxException, UnsupportedOperationException, IOException{
        /*
         * AK/SK demo code
         * */
        String AK=ACCESS_KEY_ID; //AK from authentication
        String SK=SECRET_ACCESS_KEY; //SK from authentication
        String regionName=PROJECTNAME; //region name of the service
        String  urlType = HuaweiOcrConstant.URL_PATH_DRIVER_LICENSE;
        String httpUri = getURL( urlType);
        String imgPath = "./data/vat-invoice-demo.jpg"; //File path or URL of the image to be recognized.

        // Set params except image
        JSONObject params = new JSONObject();
        List<String> typeList = new ArrayList<>();
        typeList.add("vat_invoice");
        typeList.add("id_card_portrait_side");
        params.put("type_list", typeList);

        try {
            HWOcrClientAKSK ocrClient=new HWOcrClientAKSK(regionName, AK, SK);
            HttpResponse response=ocrClient.RequestOcrServiceBase64(httpUri, imgPath, params);
//            LOGGER.info("HuaweiOcrService AkskRequest response :{}",response);
            String content = IOUtils.toString(response.getEntity().getContent(), "utf-8");
//            LOGGER.info("HuaweiOcrService AkskRequest content :{}",content);
            return  DecodeResponse(content);
        }
        catch (Exception e) {
            LOGGER.info("HuaweiOcrService AkskRequest Exception :{}",e.getMessage());
        }
        return StringUtils.EMPTY;
    }

    private static String DecodeResponse(String response) {
        JSONObject responseObject = JSONObject.parseObject(response);
//        LOGGER.info("HuaweiOcrService DecodeResponse response :{}",JSONObject.toJSONString(response));
        String result = responseObject.getString("result");
        if(StringUtils.isNotEmpty(result)){
            return result;
        }

        if(StringUtils.isNotEmpty(responseObject.getString("error_code"))){
           String errorCode =  responseObject.getString("error_code");
           if(errorCode.equals("AIS.0102")){
               throw new JeecgBootException("图片格式不支持!");
           }else if(errorCode.equals("AIS.0104")){
               throw new JeecgBootException("非支持的图片类型或图片质量差!");
           }
        }
        return StringUtils.EMPTY;
    }
}
